package com.example.springboot.select;

import com.example.springboot.auto.TestAutoConfiguration;
import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author: huangjiazhen
 * @create: 2023/1/12 9:19
 * @description:
 **/
public class TestImportSelect implements DeferredImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // 从 AutoConfiguration 文件中获取自动配置类的名字
        // 主程序通过java.util.ServiceLoder动态装载实现模块，
        // 它通过扫描META-INF/services目录下的配置文件找到实现类的全限定名，把类加载到JVM
        ServiceLoader<TestAutoConfiguration> serviceLoader = ServiceLoader.load(TestAutoConfiguration.class);
        // 导入到spring容器中
        List<String> list = new ArrayList<>();
        for (TestAutoConfiguration testAutoConfiguration : serviceLoader) {
            list.add(testAutoConfiguration.getClass().getName());
        }
        return list.toArray(new String[0]);
    }
}
